#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"

// 地址的文件名需要写全，即不要漏了.txt，否则下面的ifstream in将打不开，我这里不会打印消息
const std::string default_dict_path = "./dictionary.txt";
const std::string split = ":";
extern Log lg;
// Log lg;

static bool Split(const std::string &str, std::string &s1, std::string &s2)
// static bool Split(std::string &str, std::string *s1, std::string *s2)
{
    // auto pos = str.find(":");
    auto pos = str.find(split);
    if (pos == std::string::npos)
        return false;
    // *s1 = str.substr(0, pos);
    // *s2 = str.substr(pos+1);
    s1 = str.substr(0, pos);
    s2 = str.substr(pos + 1);
    return true;
}

class Init
{
public:
    // Init(const std::string dict_path = default_dict_path)
    Init()
    {
        // std::ifstream in(dict_path); // 只能是in不能是其他
        std::ifstream in(default_dict_path); // 无需用户自己输入，这里直接写死
        if (!in.is_open())
        {
            lg(Fatal, "Init, ifstream open %s error, errno: %d", default_dict_path.c_str(), errno);

            // std::cout<<""

            // 此处如果打不开，将直接退出，这样锁定此处的错误就很麻烦，直接运行./server也不会报错
            // exit(1);
        }
        std::string str;
        while (std::getline(in, str))
        {
            std::string s1, s2;
            Split(str, s1, s2);
            // Split(str, &s1, &s2);
            dict_.insert({s1, s2});
        }

        in.close();
    }

    std::string Translation(const std::string &key)
    {
        auto ret = dict_.find(key);
        if (ret == dict_.end())
            return "Unknow";
        return ret->second;
    }

private:
    std::unordered_map<std::string, std::string> dict_;
};